package com.prestamo.go.android.http

import android.util.Base64
import com.estrend.redbird.BuildConfig
import com.estrend.redbird.Constants
import com.estrend.redbird.R
import com.estrend.redbird.RedBirdApplication
import com.estrend.redbird.extend.toHexString
import com.estrend.redbird.net.SessionIdManager
import com.estrend.redbird.utils.AesUtils
import com.estrend.redbird.utils.BaseDecode
import com.estrend.redbird.utils.DeviceUtils
import com.estrend.redbird.utils.HMacUtils
import com.estrend.redbird.utils.RequestBuilder
import com.orhanobut.logger.Logger
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import java.security.MessageDigest



class EncryptInterceptor : Interceptor {
    @OptIn(ExperimentalStdlibApi::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()

        val builder = originalRequest.newBuilder()

        val token = RequestBuilder()
            .addParam(SessionIdManager.getToken())//会话的UUID
            .addParam(RedBirdApplication.mContext.resources.getString(R.string.app_name))//app名称
            .addParam(BuildConfig.APPLICATION_ID)//包名
            .addParam(BuildConfig.VERSION_NAME)//version
            .addParam(BuildConfig.VERSION_CODE.toString())//versionCode
            .addParam("0")//cpi
            .addParam("1")//客户端类型
            .addParam("cl")//国别代码
            .build()
        val encodeToken = Base64.encodeToString(token.toByteArray(), Base64.NO_PADDING or Base64.NO_WRAP or Base64.URL_SAFE)
        val deviceId = DeviceUtils.getDeviceUniqueId(RedBirdApplication.mContext)
        val timestamp = System.currentTimeMillis().toString()
        val userToken =SessionIdManager.getUserToken()
        builder.addHeader("Content-Type", "application/octet-stream")
        builder.addHeader("disobedience", BaseDecode.encodeFromBase64(encodeToken))
        builder.addHeader("forth", deviceId)
        builder.addHeader("go", timestamp)
        builder.addHeader("observation", SessionIdManager.getServiceConstant())
        val body = originalRequest.body
        val sha1 = if (body != null && body.contentLength() > 0) {
            val buffer = Buffer()
            body.writeTo(buffer)
            val encodeParams = Base64.encode(buffer.readByteArray(), Base64.NO_WRAP)
            val newRequestBody = RequestBody.create(
                "application/octet-stream".toMediaTypeOrNull(),
                encodeParams
            )
            builder.method(originalRequest.method, newRequestBody)
            if (BuildConfig.DEBUG) {
                Logger.i("OKHttp", "request encode params----->${String(encodeParams)}")
            }
            MessageDigest.getInstance("SHA").digest(encodeParams).toHexString()
        } else {
            ""
        }
        val raw = SessionIdManager.getToken()+userToken+deviceId+sha1+timestamp;
        val encodeSignature = HMacUtils.generateHmac(raw.toByteArray(), Constants.SECRET_KEY.toByteArray(),HMacUtils.HMAC_SHA1)
        builder.addHeader("apolitical", encodeSignature)
        return chain.proceed(builder.build())
    }
}
